const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const helper = require('../../util/helper');
const stringUtils = require('../../core/util/StringUtils');
const _ = require('lodash');

exports.add = async(ctx) => {
    let manager_name = ctx.request.body.manager_name ? ctx.request.body.manager_name.trim() : '';
    let nick_name = ctx.request.body.nick_name || '';
    let password = ctx.request.body.password || '';
    let role_id = ctx.request.body.role_id || '';
    let email = ctx.request.body.email || '';
    let phone = ctx.request.body.phone || '';
    let group_id = ctx.request.body.group_id || 0;
    let create_manager_id = ctx.user.id || 0;
    if (manager_name === '' || password === ''  || role_id === '' || create_manager_id === 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    let salt = helper.makeSalt();
    let hash_password = helper.encryptPassword(password, salt);
    let newManager = {
        manager_name,
        salt,
        email,
        hash_password,
        role_id,
        phone,
        nick_name,
        group_id,
        create_manager_id,
        create_time:moment().format('YYYY-MM-DD HH:mm:ss'),
        update_time:moment().format('YYYY-MM-DD HH:mm:ss')
    };
    try{
        let selectManager = await mysql.query(`select * from manager where manager_name = ? `, manager_name);
        if (selectManager.length > 0){
            ctx.body = {
                result: 203,
                message: "此帐号已存在"
            };
            return;
        }
        let ret = await mysql.query(`INSERT INTO manager SET ?`, newManager);
        if (!ret || ret.insertId === -1){
            ctx.body = {
                result: 204,
                message: "新增账号失败"
            };
        } else {
            ctx.body = {
                result: 200,
                id: ret.insertId,
                message: "新增账号成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.delete = async(ctx) => {
    let manager_id = ctx.params.manager_id || 0;
    if (manager_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        ret = await mysql.query(`delete from manager WHERE manager_id = ?`, manager_id);
        if (!ret || ret.affectedRows === 0){
            ctx.body = {
                result: 202,
                message: "对象不存在或已删除"
            };
        } else {
            ctx.body = {
                result: 200,
                message: "删除成功"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let manager_id = ctx.request.body.manager_id || 0;
    let manager_name = ctx.request.body.manager_name || '';
    let phone = ctx.request.body.phone || '';
    let role_id = ctx.request.body.role_id;
    let email = ctx.request.body.email || '';
    let nick_name = ctx.request.body.nick_name || '';
    let group_id = ctx.request.body.group_id || 0;
    // let create_manager_id = ctx.user.id || 0;
    if (manager_id === 0 || !role_id ) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try {
        let selectRows = await mysql.query(`SELECT * FROM manager WHERE manager_id = ?`, manager_id);
        if (selectRows.length > 0) {
            console.log('selectRows:', selectRows);
            let salt = helper.makeSalt();
            selectRows[0].manager_name = manager_name;
            selectRows[0].nick_name = nick_name;
            selectRows[0].role_id = role_id;
            selectRows[0].phone = phone;
            selectRows[0].email = email;
            selectRows[0].group_id = group_id;
            selectRows[0].update_time = moment().format('YYYY-MM-DD HH:mm:ss');
            ret = await mysql.query(`UPDATE manager SET ? WHERE manager_id= ? `, [selectRows[0],manager_id]);
            console.log(ret);
            if (!ret || ret.affectedRows === 0) {
                ctx.body = {
                    result: 202,
                    message: "更新失败"
                };
            } else {
                ctx.body = {
                    result: 200,
                    message: "更新成功"
                };
            }
        } else {
            ctx.body = {
                result: 203,
                message: "对象不存在或者已删除"
            };
        }
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "错误"+e.toString()
        };
    }
}


exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;

    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            let results = await mysql.query(`SELECT * FROM v_manager_detail ORDER BY manager_id DESC LIMIT ${indexfrom}, ${counts} ` );
            let totalResult = await mysql.query(`SELECT COUNT(manager_id) AS total FROM v_manager_detail `);
            ctx.body = {
                result: 200,
                list:results,
                totalpage:Math.ceil((totalResult.length > 0 ? totalResult[0].total : 0)/counts),
                totalcounts:totalResult.length > 0 ? totalResult[0].total : 0,
                message: "查询成功"
            };
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误 " + e.toString()
            };
        }
    }
}

exports.changePassword = async(ctx) => {
    let old_password = ctx.request.body.old_password || '';
    let new_password = ctx.request.body.new_password || '';
    let user_id = ctx.user.id || '';

    if (old_password === '' || new_password === '' || user_id === '' ){

        ctx.body = {
            result: 201,
            message: "请传入正确参数"
        };
    } else {
        try {
            let selectRows = await mysql.query(`SELECT * FROM manager WHERE manager_id = ?`, user_id);
            let salt = selectRows[0].salt;
            let old_password1 = helper.encryptPassword(old_password, salt);
            if (selectRows[0].hash_password !== old_password1) {
                ctx.body = {
                    result: 202,
                    message: "原始密码不正确"
                };
            }
            else {
                let new_password1 = helper.encryptPassword(new_password, salt);
                let ret = await mysql.query(`UPDATE manager SET hash_password = '${new_password1}'  WHERE manager_id= ? `, user_id);
                if (!ret || ret.affectedRows === 0) {
                    ctx.body = {
                        result: 202,
                        message: "更新失败"
                    };
                } else {
                    ctx.body = {
                        result: 200,
                        message: "更新成功"
                    };
                }
            }

        }catch (e) {
            ctx.body = {
                result: 205,
                message: "错误 " + e.toString()
            };
        }
    }

}
